package com.to8to.autotask.lundan;

import java.util.ArrayList;
import java.util.List;

import com.google.common.collect.Lists;

public class RoundRobinQueue<T> {

	private int head;
	
	private List<T> list = new ArrayList<T>();
	
	public RoundRobinQueue(List<T> list)
	{
		this.list = list;
	}
	
	private void next(int num)
	{
		if(list.size() == 0)
			return;
		
		head = head + num;
		if(head >= list.size())
			head = head % list.size();
	}
	
	public List<T> poll(int num)
	{
		num = Math.min(num, list.size());
		
		List<T> results = new ArrayList<T>(num);
		
		for(; results.size() < num; next(1))
		{
			T item = list.get(head);
			results.add(item);
		}
		
		return results;
	}
	
	
	public static void main(String[] args)
	{
		RoundRobinQueue<Integer> queue = new RoundRobinQueue<Integer>(Lists.newArrayList(1,2,3,4,5,6,7));
		
		List<Integer> heads = queue.poll(2);
		
		System.out.println(heads);
		
		heads = queue.poll(2);
		
		System.out.println(heads);
		
		heads = queue.poll(2);
		
		System.out.println(heads);
		
		heads = queue.poll(3);
		
		System.out.println(heads);
		
		heads = queue.poll(7);
		
		System.out.println(heads);
	}
}
